/*
 * Copyright (C) 2017-2021
 * All rights reserved, Designed By
 * Copyright authorization contact 18814114118
 */
package com.shop.cereshop.commons.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.shop.cereshop.commons.domain.buyer.CereBuyerReceive;
import com.shop.cereshop.commons.domain.express.HttpResult;
import com.shop.cereshop.commons.domain.shop.CerePlatformShop;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 运费计算工具类
 * 支持三种类型的运费计算：
 * 1. 到店核销（type=1）：免运费
 * 2. 电商购（type=2）：调用快递100商家寄件下单价格接口
 * 3. 同城送（type=3）：调用快递100同城配送预下单接口
 */
@Slf4j
public class DistributionPriceUtil {

    /**
     * 计算运费
     * 
     * @param type 商品售卖类型 1-到店核销 2-电商购 3-同城送
     * @param key 快递100密钥
     * @param secret 快递100密钥secret
     * @param shop 店铺信息
     * @param receive 收货地址信息
     * @param totalWeight 总重量（单位：kg）
     * @param totalPrice 商品总价（用于同城配送）
     * @param goodsList 选中的商品列表（用于同城配送）
     * @return 运费金额（单位：元）
     */
    public static BigDecimal calculateDistributionPrice(
            Integer type,
            String key,
            String secret,
            CerePlatformShop shop,
            CereBuyerReceive receive,
            BigDecimal totalWeight,
            BigDecimal totalPrice,
            List<GoodsItem> goodsList) {
        
        if (type == null) {
            return BigDecimal.ZERO;
        }
        
        // 1. 到店核销：免运费
        if (type == 1) {
            return BigDecimal.ZERO;
        }
        
        // 2. 电商购：调用快递100商家寄件下单价格接口
        if (type == 2) {
            return calculateEcommerceDistributionPrice(key, secret, shop, receive, totalWeight);
        }
        
        // 3. 同城送：调用快递100同城配送预下单接口
        if (type == 3) {
            return calculateSameCityDistributionPrice(key, secret, shop, receive, totalWeight, totalPrice, goodsList);
        }
        
        return BigDecimal.ZERO;
    }
    
    /**
     * 计算电商购运费
     */
    private static BigDecimal calculateEcommerceDistributionPrice(
            String key,
            String secret,
            CerePlatformShop shop,
            CereBuyerReceive receive,
            BigDecimal totalWeight) {
        
        if (shop == null || receive == null || totalWeight == null || totalWeight.compareTo(BigDecimal.ZERO) <= 0) {
            return BigDecimal.ZERO;
        }
        
        try {
            String shopAddress = shop.getShopAdress()+" "+ shop.getShopAdressDetail();
            String userAddress  = receive.getReceiveAdress()+" "+ receive.getAddress();

            if (StringUtils.isBlank(shopAddress) || StringUtils.isBlank(userAddress)) {
                return BigDecimal.ZERO;
            }
            
            // 构建快递100请求参数
            Kuaidi100SendOrderPriceUtil.SendOrderPriceParam priceParam = new Kuaidi100SendOrderPriceUtil.SendOrderPriceParam();
            priceParam.setKuaidicom("zhongtong"); // 默认使用中通，可根据实际情况从店铺配置中获取
            priceParam.setSendManName(shop.getChargePersonName() != null ? shop.getChargePersonName() : "商家");
            priceParam.setSendManMobile(shop.getChargePersonPhone() != null ? shop.getChargePersonPhone() : "");
            priceParam.setSendManPrintAddr(shopAddress);
            priceParam.setRecManName(receive.getReceiveName() != null ? receive.getReceiveName() : "");
            priceParam.setRecManMobile(receive.getReceivePhone() != null ? receive.getReceivePhone() : "");
            priceParam.setRecManPrintAddr(userAddress);
            priceParam.setWeight(totalWeight.toString());
            
            // 调用快递100接口获取运费
            return Kuaidi100SendOrderPriceUtil.getSendOrderPrice(key, secret, priceParam);
        } catch (Exception e) {
            log.error("计算电商购运费失败", e);
            return BigDecimal.ZERO;
        }
    }
    
    /**
     * 同城配送请求参数
     */
    @Data
    private static class SameCityPriceParam {
        /**
         * 快递公司编码，同城配送使用 shunfengtongcheng
         */
        private String kuaidicom;
        
        /**
         * 回调地址
         */
        private String callbackUrl;
        
        /**
         * 收件人姓名
         */
        private String recManName;
        
        /**
         * 收件人电话
         */
        private String recManMobile;
        
        /**
         * 收件人省份
         */
        private String recManProvince;
        
        /**
         * 收件人城市
         */
        private String recManCity;
        
        /**
         * 收件人区县
         */
        private String recManDistrict;
        
        /**
         * 收件人经度
         */
        private String recManLng;
        
        /**
         * 收件人纬度
         */
        private String recManLat;
        
        /**
         * 收件人地址
         */
        private String recManAddr;
        
        /**
         * 寄件人经度
         */
        private String sendManLng;
        
        /**
         * 寄件人纬度
         */
        private String sendManLat;
        
        /**
         * LBS类型：2-经纬度
         */
        private Integer lbsType;
        
        /**
         * 寄件人姓名
         */
        private String sendManName;
        
        /**
         * 寄件人电话
         */
        private String sendManMobile;
        
        /**
         * 寄件人省份
         */
        private String sendManProvince;
        
        /**
         * 寄件人城市
         */
        private String sendManCity;
        
        /**
         * 寄件人区县
         */
        private String sendManDistrict;
        
        /**
         * 寄件人地址
         */
        private String sendManAddr;
        
        /**
         * 商品价格
         */
        private String price;
        
        /**
         * 重量（单位：kg）
         */
        private String weight;
        
        /**
         * 商品列表
         */
        private List<GoodsItem> goods;
    }
    

    
    /**
     * 同城配送响应结果
     */
    @Data
    private static class SameCityPriceResponse {
        /**
         * 是否成功
         */
        private Boolean result;
        
        /**
         * 返回码
         */
        private String returnCode;
        
        /**
         * 返回消息
         */
        private String message;
        
        /**
         * 返回数据
         */
        private JSONObject data;
    }
    
    /**
     * 请求对象
     */
    @Data
    private static class SameCityPriceRequest {
        private String key;
        private String sign;
        private String t;
        private String param;
        private String method;
    }
    
    /**
     * 计算同城送运费
     * 接口地址：https://poll.kuaidi100.com/order/borderapi.do
     * method: bsamecityPrice
     */
    private static BigDecimal calculateSameCityDistributionPrice(
            String key,
            String secret,
            CerePlatformShop shop,
            CereBuyerReceive receive,
            BigDecimal totalWeight,
            BigDecimal totalPrice,
            List<GoodsItem> goodsList) {
        
        if (shop == null || receive == null) {
            return BigDecimal.ZERO;
        }
        
        try {
            // 解析收货地址

            
            // 解析收货地址经纬度
            String[] locations = null;
            if (StringUtils.isNotBlank(receive.getLocation())) {
                locations = receive.getLocation().split(",");
            }
            if (locations == null || locations.length < 2) {
                log.error("收货地址经纬度错误: {}", receive.getLocation());
                return BigDecimal.ZERO;
            }
            
            // 解析店铺经纬度
            String[] shopLocations = null;
            if (StringUtils.isNotBlank(shop.getLocation())) {
                shopLocations = shop.getLocation().split(",");
            }
            if (shopLocations == null || shopLocations.length < 2) {
                log.error("店铺地址经纬度错误: {}", shop.getLocation());
                return BigDecimal.ZERO;
            }
            
            // 构建同城配送请求参数
            SameCityPriceParam param = new SameCityPriceParam();
            param.setKuaidicom("shansongtongcheng"); // 顺丰同城
            
            // 收件人信息
            param.setRecManName(receive.getReceiveName() != null ? receive.getReceiveName() : "");
            param.setRecManMobile(receive.getReceivePhone() != null ? receive.getReceivePhone() : "");
            param.setRecManProvince(receive.getProvince());
            param.setRecManCity(receive.getCity());
            param.setRecManDistrict(receive.getDistrict());

            param.setRecManLng(locations[0].substring(0, Math.min(10, locations[0].length())));//收件人地址经度，只保留前10位
            param.setRecManLat(locations[1].substring(0, Math.min(10, locations[1].length())));//收件人地址纬度，只保留前10位
            String userAddress = receive.getAddress();
            param.setRecManAddr(userAddress);
            
            // 寄件人信息（商家）
            param.setSendManLng(shopLocations[0].substring(0, Math.min(10, shopLocations[0].length())));
            param.setSendManLat(shopLocations[1].substring(0, Math.min(10, shopLocations[1].length())));

            param.setLbsType(2); // LBS类型：2-经纬度
            param.setSendManName(shop.getChargePersonName() != null ? shop.getChargePersonName() : shop.getShopName());
            param.setSendManMobile(shop.getChargePersonPhone() != null ? shop.getChargePersonPhone() : "");
            param.setSendManProvince(shop.getShopAdressProvince() != null ? shop.getShopAdressProvince() : "");
            param.setSendManCity(shop.getShopAdressCity() != null ? shop.getShopAdressCity() : "");
            param.setSendManDistrict(shop.getShopAddressDist() != null ? shop.getShopAddressDist() : "");
            String shopAddress = shop.getShopAdressDetail();
            param.setSendManAddr(shopAddress);
            
            // 商品信息
            if (totalPrice != null) {
                param.setPrice(totalPrice.toString());
            }
            if (totalWeight != null) {
                param.setWeight(totalWeight.toString());
            }
            
            // 商品列表
            param.setGoods(goodsList);
            
            // 生成时间戳
            String t = String.valueOf(System.currentTimeMillis());
            
            // 构建param JSON字符串
            String paramJson = new Gson().toJson(param);
            
            // 计算签名：MD5(param + t + key + secret).toUpperCase()
            String sign = DigestUtils.md5Hex(paramJson + t + key + secret).toUpperCase();
            
            // 构建请求对象
            SameCityPriceRequest request = new SameCityPriceRequest();
            request.setKey(key);
            request.setSign(sign);
            request.setT(t);
            request.setParam(paramJson);
            request.setMethod("price"); // 同城配送预下单接口的method
            
            // 调用接口
            String url = "https://api.kuaidi100.com/bsamecity/order";
            HttpResult httpResult = HttpUtils.doPost(url, request);
            
            if (httpResult.getStatus() == 200 && StringUtils.isNotBlank(httpResult.getBody())) {
                SameCityPriceResponse response = JSON.parseObject(httpResult.getBody(), SameCityPriceResponse.class);
                
                if (response != null) {
                    // 接口调用成功，从data中获取运费
                    if (response.getData() != null) {
                        // 运费字段可能是 deliverFee 或 fee
                        String deliverFee = response.getData().getString("discountFee");
                        if (StringUtils.isNotBlank(deliverFee)) {
                            try {
                                return new BigDecimal(deliverFee);
                            } catch (Exception e) {
                                log.error("解析同城配送运费失败: {}", deliverFee, e);
                                return BigDecimal.ZERO;
                            }
                        } else {
                            log.warn("同城配送预下单接口返回成功但运费字段为空");
                            return BigDecimal.ZERO;
                        }
                    } else {
                        log.warn("同城配送预下单接口返回成功但data为空");
                        return BigDecimal.ZERO;
                    }
                } else {
                    // 接口返回失败
                    String errorMsg = response != null ? response.getMessage() : "未知错误";
                    log.error("同城配送预下单接口调用失败: {}", errorMsg);
                    return BigDecimal.ZERO;
                }
            } else {
                log.error("同城配送预下单接口HTTP请求失败: status={}, body={}", 
                        httpResult.getStatus(), httpResult.getBody());
                return BigDecimal.ZERO;
            }
        } catch (Exception e) {
            log.error("计算同城送运费失败", e);
            return BigDecimal.ZERO;
        }
    }
}

